package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.mapper.UserMapper;
import cn.tedu.coolshark.pojo.dto.UserDto;
import cn.tedu.coolshark.pojo.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMapper mapper;

    @RequestMapping("/login")
    public int login(@RequestBody UserDto userDto, HttpServletResponse response, HttpSession session){
        UserVo user = mapper.selectByUsername(userDto.getUsername());
        if(user!=null){
            if(userDto.getPassword().equals(user.getPassword())){
                if(userDto.getRem()){
                    Cookie c1 = new Cookie("username", userDto.getUsername());
                    Cookie c2 = new Cookie("password", userDto.getPassword());
                    c1.setMaxAge(60*60*24*15);//半个月，单位是秒
                    c1.setPath("/");
                    c2.setPath("/");
                    //把cookie响应给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                session.setAttribute("user",user);
                return 1;
            }
            return 2;
        }
        return 3;
    }

    @RequestMapping("/currentUser")
    public UserVo currentUser(HttpSession session){
        return (UserVo)session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
